// pages/login/index.js
const common = require('../../public.js')
const config = require('../../config')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showPrivacy: false,
    loginLogo: config.loginLogo
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //获得胶囊位置，设置返回按钮
    const capsule = wx.getMenuButtonBoundingClientRect()
    this.setData({
      topOffset: capsule.top,
      height: capsule.height
    })
    if (options.backUrl) {
      this.data.backUrl = decodeURIComponent(options.backUrl)
    }
  },

  login() {
    const that = this
    // 调用登录方法，这里需要传入返回的url
    common.loginFunc(this.data.backUrl).then(function (loginSucessed) {
      if (loginSucessed) {
        that.popPage(true)
      } else {
        const backUrl = config.myCenterUrl ? '/' + config.myCenterUrl : '/pages/mySelf/Index/index'
        wx.switchTab({
          url: backUrl,
          success() {
            common.showToast('登录失败')
          }
        })
      }
    })
  },
  // 返回指定界面
  popPage(showToast = false) {
    const that = this
    if (that.data.backUrl) {
      wx.redirectTo({
        url: that.data.backUrl,
        success() {
          showToast && common.showToast('登录成功')
        }
      })
    } else {
      wx.navigateBack({ // 返会上个界面
        delta: 1,
        success() {
          showToast && common.showToast('登录成功')
        }
      })
    }
  },
  cancel() {
    const backUrl = config.myCenterUrl ? '/' + config.myCenterUrl : '/pages/mySelf/Index/index'
    wx.switchTab({
      url: backUrl
    })
  },
  showPrivacy() {
    this.setData({
      showPrivacy: true
    })
  },
  closePrivacy() {
    this.setData({
      showPrivacy: false
    })
  }
})